package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.ServletUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.common.utils.ip.IpUtils;
import cn.sfrog.project.biz.admin.domain.BizUserEnsureMoney;
import cn.sfrog.project.biz.admin.domain.BizUserRechargePayment;
import cn.sfrog.project.biz.admin.domain.vo.BizUserEnsureMoneyAuditVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserEnsureMoneyFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserEnsureMoneyQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserEnsureMoneyVO;
import cn.sfrog.project.biz.admin.enums.BizSureMoneyStatusEnum;
import cn.sfrog.project.biz.admin.enums.BizUserTradeTypeEnum;
import cn.sfrog.project.biz.admin.enums.PayMethodEnum;
import cn.sfrog.project.biz.admin.mapper.BizUserEnsureMoneyMapper;
import cn.sfrog.project.biz.admin.pay.PayFactory;
import cn.sfrog.project.biz.admin.service.IBizUserEnsureMoneyService;
import cn.sfrog.project.biz.admin.service.IBizUserRechargePaymentService;
import cn.sfrog.project.biz.admin.service.IBizUserTradeRecordService;
import cn.sfrog.project.biz.web.vo.money.AppPaymentEarnestMoneyFormVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 保证金Service业务层处理
 */
@Slf4j
@Service
public class BizUserEnsureMoneyServiceImpl extends ServiceImpl<BizUserEnsureMoneyMapper, BizUserEnsureMoney> implements IBizUserEnsureMoneyService {
    @Resource
    private BizUserEnsureMoneyMapper bizUserEnsureMoneyMapper;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBizUserRechargePaymentService bizUserRechargePaymentService;
    @Autowired
    private IBizUserTradeRecordService bizUserTradeRecordService;

    @Value("${wxPay.appId}")
    private String appId;

    @Value("${wxPay.mchId}")
    private String mchId;
    @Value("${wxPay.secret}")
    private String secret;

    @Value("${wxPay.notifyUrl}")
    private String notifyUrl;

    /**
     * 查询保证金
     *
     * @param id 保证金主键
     * @return 保证金
     */
    @Override
    public BizUserEnsureMoneyVO selectBizUserEnsureMoneyById(Long id) {
        return bizUserEnsureMoneyMapper.selectBizUserEnsureMoneyById(id);
    }

    /**
     * 查询保证金列表
     *
     * @param query 保证金
     * @return 保证金
     */
    @Override
    public List<BizUserEnsureMoneyVO> selectBizUserEnsureMoneyList(BizUserEnsureMoneyQueryVO query) {
        return bizUserEnsureMoneyMapper.selectBizUserEnsureMoneyList(query);
    }

    /**
     * 新增保证金
     *
     * @param form 保证金
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizUserEnsureMoney(BizUserEnsureMoneyFormVO form) {
        BizUserEnsureMoney bizUserEnsureMoney = new BizUserEnsureMoney();
        BeanUtils.copyProperties(form, bizUserEnsureMoney);
        bizUserEnsureMoney.setCreateTime(new Date());
        bizUserEnsureMoney.setCreateBy(SecurityUtils.getUsername());
        bizUserEnsureMoney.setUpdateTime(new Date());
        bizUserEnsureMoney.setUpdateBy(SecurityUtils.getUsername());
        return bizUserEnsureMoney.insert();
    }

    /**
     * 修改保证金
     *
     * @param form 保证金
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizUserEnsureMoney(BizUserEnsureMoneyFormVO form) {
        BizUserEnsureMoney bizUserEnsureMoney = new BizUserEnsureMoney();
        BeanUtils.copyProperties(form, bizUserEnsureMoney);
        bizUserEnsureMoney.setUpdateTime(new Date());
        bizUserEnsureMoney.setUpdateBy(SecurityUtils.getUsername());
        return bizUserEnsureMoney.updateById();
    }

    /**
     * 批量删除保证金
     *
     * @param ids 需要删除的保证金主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizUserEnsureMoneyByIds(Long[] ids) {
            return BizUserEnsureMoney.DAO.delete(Wrappers.lambdaQuery(BizUserEnsureMoney.class).in(BizUserEnsureMoney::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
//        return BizUserEnsureMoney.DAO.update(Wrappers.lambdaUpdate(BizUserEnsureMoney.class).in(BizUserEnsureMoney::getId, (Object[]) vo.getIds()).set(BizUserEnsureMoney::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int audit(BizUserEnsureMoneyAuditVO auditVO) {
        BizUserEnsureMoney money = BizUserEnsureMoney.DAO.selectById(auditVO.getId());
        BizUserEnsureMoney bizUserEnsureMoney = new BizUserEnsureMoney();
        bizUserEnsureMoney.setId(auditVO.getId());
        bizUserEnsureMoney.setRefundAuditStatus(auditVO.getRefundAuditStatus());
        bizUserEnsureMoney.setRefundRemark(auditVO.getRefundRemark());
        if(BizUserEnsureMoney.REFUND_AUDIT_STATUS_SUCCESS.equals(auditVO.getRefundAuditStatus())){
            // TODO: 2022/9/7 审核通过 要进行退款
            bizUserEnsureMoney.setPayStatus(BizSureMoneyStatusEnum.RETURNED.getCode());
            bizUserTradeRecordService.saveUserTradeRecord(money.getUserId(),money.getAmount(), BizUserTradeTypeEnum.RETURN_MONEY.getCode(),money.getSerialNumber(),"保证金退款");
        }else {
            // TODO: 2022/9/7 这边要确认如果退款审核失败后，保证金状态怎么显示 暂时先写为回到已支付状态
            bizUserEnsureMoney.setPayStatus(BizSureMoneyStatusEnum.PAID.getCode());
        }
        return  bizUserEnsureMoney.updateById() ? 1 : 0;
    }

    @Override
    public BigDecimal selectAllUserSureAmount() {
        return bizUserEnsureMoneyMapper.selectAllUserSureAmount();
    }

    @Override
    public Map<String, String> paymentEarnestMoney(AppPaymentEarnestMoneyFormVO form) {
        Map<String, String> payParams = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        BizUserEnsureMoney userEnsureMoney = createUserEnsureMoney(user, form.getEarnestMoney());
        //保证金表
        int insert = bizUserEnsureMoneyMapper.insert(userEnsureMoney);
        if(insert > 0){
            //构造支付流水参数
            BizUserRechargePayment payment = bizUserRechargePaymentService.createEnsureMoneyPayment(userEnsureMoney,user);
            if(StringUtils.equals(Constants.PAY_TYPE_WX,form.getPayType())){
                //微信支付
                WxPayApiConfig wxPayApiConfig = WxPayApiConfig.New()
                        .setAppId(appId)
                        .setMchId(mchId)
                        .setPaternerKey(secret);
                WxPayApiConfigKit.setThreadLocalWxPayApiConfig(wxPayApiConfig);
                String[] split = IpUtils.getIpAddr(ServletUtils.getRequest()).split(",");
                String ip = split[0];
                Map<String, String> params = WxPayApiConfigKit.getApiConfig(appId)
                        .setBody("缴纳保证金")
                        .setSpbillCreateIp(ip)
                        .setTotalFee(form.getEarnestMoney().multiply(BigDecimal.valueOf(100)).setScale(0).toString())
                        .setTradeType(WxPayApi.TradeType.APP)
                        .setNotifyUrl(notifyUrl + "/app/payment/callback")
                        .setOutTradeNo(payment.getId().toString())
                        .setAttach(payment.getId().toString())
                        .build();
                System.out.println("支付参数++++"+params);
                String xmlResult = WxPayApi.pushOrder(false, params);
                log.info(xmlResult);
                Map<String, String> resultMap = PaymentKit.xmlToMap(xmlResult);
                System.out.println("+++++++++++++"+resultMap);
                String prepayId = resultMap.get("prepay_id");
                payParams = prepayIdCreateSign(prepayId);
                payParams.put("rechargeId",userEnsureMoney.getId().toString());
            }else if(StringUtils.equals(Constants.PAY_TYPE_ALIPAY,form.getPayType())){
                PayFactory payService = PayFactory.getPayService(PayMethodEnum.ALI_PAY);
                String s = payService.buildPayParams(payment.getRechargeSerialNumber(), payment.getPaymentAmount());
                payParams.put("aLiPayParams",s);
                payParams.put("rechargeId",userEnsureMoney.getId().toString());
            }
        }

        return payParams;
    }

    @Override
    public Boolean applyReturnMoney() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BizUserEnsureMoney> lambdaQueryWrapper = new LambdaQueryWrapper<BizUserEnsureMoney>()
                .eq(BizUserEnsureMoney::getUserId,userId)
                .orderByDesc(BizUserEnsureMoney::getCreateTime)
                .last(" limit 1");
        BizUserEnsureMoney money = BizUserEnsureMoney.DAO.selectOne(lambdaQueryWrapper);
        if(money == null){
            throw new ApiException("保证金不存在");
        }
        if(money.getRefundAuditStatus() != null && "0".equals(money.getRefundAuditStatus())){
            throw new ApiException("保证金已经在退款审核中了");
        }
        money.setPayStatus(BizUserEnsureMoney.REFUNDING);
        money.setRefundAuditStatus(BizUserEnsureMoney.REFUND_AUDIT_STATUS_WAIT);
        money.setUpdateTime(DateUtils.getNowDate());
        money.setUpdateBy(userId.toString());
        return money.updateById();
    }

    public Map<String, String> prepayIdCreateSign(String prepay_id) {
        Map<String, String> packageParams = new HashMap<String, String>();
        packageParams.put("appid", WxPayApiConfigKit.getWxPayApiConfig().getAppId());
        packageParams.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        packageParams.put("noncestr", String.valueOf(System.currentTimeMillis()));
        packageParams.put("package", "Sign=WXPay");
        packageParams.put("partnerid",mchId);
        packageParams.put("prepayid",prepay_id);
        String packageSign = PaymentKit.createSign(packageParams,
                WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey());
        packageParams.put("paySign", packageSign);
        return packageParams;
    }


    public BizUserEnsureMoney createUserEnsureMoney(SysUser user,BigDecimal earnestMoney){
        BizUserEnsureMoney money = new BizUserEnsureMoney();
        money.setUserId(user.getUserId());
        money.setUserName(user.getNickName());
        money.setType(user.getUserType());
        money.setSerialNumber(redisCache.buildEnsureMoneySerialNumber());
        money.setPhone(user.getPhonenumber());
        money.setAmount(earnestMoney);
        money.setCreateBy(user.getUserName());
        money.setCreateTime(DateUtils.getNowDate());
        money.setUpdateBy(user.getUserName());
        money.setUpdateTime(DateUtils.getNowDate());
        return money;
    }

}
